// import axios, {
//   AxiosInstance,
//   AxiosResponse,
//   AxiosRequestConfig,
//   AxiosError
// } from 'axios'
import axios, { AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import store from '@/store'
import { useRouter } from 'vue-router'
import { provide } from 'vue'


const service = axios.create({
  baseURL: (import.meta.env.VITE_APP_BASE_URL) as string,
  timeout: 10000,
  withCredentials: true
})

service.interceptors.request.use((config: AxiosRequestConfig) => {
  config.headers['Content-Type'] = 'application/json;charset=utf-8'
  if(store.state.user.loginUserObj != null) {
     config.headers['accessToken'] = store.state.user.loginUserObj.accessToken
  }
  return config
}, (error) => Promise.reject(error))

service.interceptors.response.use((response: { data: any; }) => {
    const res = response.data
    if (res.code && (res.code === 888)) {
      // 非法用户
      window.location.href = '/error/illegal-user'
    }
    if (res.code && (res.code === 102 || res.code === 103)) {
      ElMessage({
        message: res.msg,
        type: 'error',
        duration: 5 * 1000
      })
      // return Promise.reject('error')
      return Promise.resolve({
        isError: true,
        errorMsg: res.msg,
        isNetError: false
      })
    } else {
      return res 
    }
  },
  (error: { message: any; }) => {
    console.log(`err${error}`) // for debug
    ElMessage({
      message: '网络异常，请重试！',
      type: 'error',
      duration: 5 * 1000
    })
    // message.error('网络异常，请重试！')
    // return Promise.reject(error)
    
    return Promise.reject({
      isError: true,
      errorMsg: error.message,
      isNetError: true
    })
  }
)

export default service
